# Check the residuals of the models in the main text and ensure that the linear time trends assmption
# hold. See Appendix J.




#############
# residuals #
#############

library(brms)
library(ggplot2)
library(ggpubr)
library(stargazer)

# load stan fits
load("PSRM Replication Files/Stan_15Days.RData")


# function to plot residuals
plotResid2 <- function(model, name){
  data <- model$data
  data$residual <- residuals(model)[,1]
  
  data$days <- data$Xl
  data$days[which(data$post == 1)] <- data$Xr[which(data$post == 1)]
  
  pre <- data[which(data$post == 0),]
  post <- data[which(data$post == 1),]
  
  plot(data$days, data$residual, pch=".",
       main=name,
       xlab="Days since the Election", ylab="Residual")
  abline(v=0, lty=2)
  lines(loess.smooth(pre$days, pre$residual, span=1/3), col="red", lwd=2)
  lines(loess.smooth(post$days, post$residual, span=1/3), col="red", lwd=2)
}

# figure J.1
#pdf("residuals.pdf", width=12, height=6)
par(mfrow=c(2,4))
plotResid2(winner_love1, "Winner + Love + No Interaction")
plotResid2(winner_angry1, "Winner + Angry + No Interaction")
plotResid2(loser_love1, "Loser + Love + No Interaction")
plotResid2(loser_angry1, "Loser + Angry + No Interaction")
plotResid2(winner_love2, "Winner + Love + Two Interactions")
plotResid2(winner_angry2, "Winner + Angry + Two Interactions")
plotResid2(loser_love2, "Loser + Love + Two Interactions")
plotResid2(loser_angry2, "Loser + Angry + Two Interactions")
#dev.off()
